#!/usr/bin/env bash
################################################################
# 環境を初期化する：
# 最初の実行でバックアップと環境の初期化が完了します。
# 2 回目の実行を実行して環境のリセットを完了します。
# ref: https://wiki.geniie.net/pages/viewpage.action?pageId=1958358140
################################################################
WORK_PATH=$(readlink -f ${0} | xargs dirname)
ART_GENIIE_USER="xiufd@neusoft.com"
ART_GENIIE_API_KEY="AP58PCMYRfT7BX8xzA7gtn3J9iB"
HTTP_PROXY="http://172.30.10.2:1080"
HTTPS_PROXY="http://172.30.10.2:1080"
NO_PROXY="localhost,127.0.0.1,172.30.10.0/24,github.com,google.com,googlesource.com,googleapis.com"

export http_proxy=${HTTP_PROXY}
export https_proxy=${HTTPS_PROXY}
# create backup directory
action="backup_init" # backup_init | reset
action_status="OK"
if [[ ! -e ${WORK_PATH}/tool/backup ]]; then
  mkdir -p ${WORK_PATH}/tool/backup
  echo "backup_init" > ${WORK_PATH}/tool/backup/action
else
  action=$(cat ${WORK_PATH}/tool/backup/action)
fi

# create or destroy user config info
user_config_list=(
  .gitconfig
  .netrc
  .curlrc
  .wgetrc
  .ssh
  .wget-hsts
  .profile
  .bash_logout
)
for conf_file in ${user_config_list[@]}; do
  if [[ "${action}" == "backup_init" ]]; then
    # backup
    if [[ -e ${HOME}/${conf_file} ]]; then 
      cp -fr ${HOME}/${conf_file} ${WORK_PATH}/tool/backup/
      rm -fr ${HOME}/${conf_file} 
    fi
    # init 
    if [[ -e ${WORK_PATH}/tool/userconfig/${conf_file} ]]; then 
      cp -fr ${WORK_PATH}/tool/userconfig/${conf_file} ${HOME}/
    else
      echo "The config file [${conf_file}] does not exist"
    fi
  else
    # reset and delete backup
    if [[ -e ${WORK_PATH}/tool/backup/${conf_file} ]]; then
      cp -fr ${WORK_PATH}/tool/backup/${conf_file} ${HOME}/
      rm -fr ${WORK_PATH}/tool/backup/${conf_file}
    else
      rm -fr ${HOME}/${conf_file}
    fi
  fi
done

# create or destroy yocto build docker
docker_image="art.geniie.net/denso-ten-ci-docker/denso-ten-ci/poky:ubuntu-20.04"
current_image_id=$(docker images -q ${docker_image})
docker_local_file="${WORK_PATH}/tool/bev-neu_poky_ubuntu-20.04.tar"
docker_backup_file="${WORK_PATH}/tool/backup/bev-neu_poky_ubuntu-20.04.tar"
if [[ "${action}" == "backup_init" ]]; then 
  # backup
  if [[ -n ${current_image_id} ]]; then 
    rm -fr ${docker_backup_file}
    docker save -o ${docker_backup_file} ${docker_image} || action_status="${LINENO} Failed to docker save."
    docker rmi -f ${current_image_id} || action_status="${LINENO} Failed to docker rmi."
  fi
  # init
  build_docker_url=https://art.geniie.net/artifactory/denso-ten-ci-docker/denso-ten-ci/poky/ubuntu-20.04/
  wget --tries=2 --connect-timeout=300 --show-progress -q -P ${WORK_PATH}/list_info ${build_docker_url} || ret=$?
  if [[ $ret -ne 0 ]]; then
    echo "error=$ret, Failed wget ${BEV_QCOM_TOOL_URL}"
  fi
  build_docker_date=$(grep "manifest.json" ${WORK_PATH}/list_info/index.html | awk '{print($3,$4)}')
  rm -fr ${WORK_PATH}/list_info
  build_docker_history_date=$(cat ${WORK_PATH}/tool/build_docker_version.txt)
  if [[ -z ${build_docker_date} ]]; then build_docker_date="22-May-2024 05:42"; fi
  if [[ "${build_docker_date}" != "${build_docker_history_date}" || ! -e ${docker_local_file} ]] ; then
    docker logout art.geniie.net
    docker login -u "${ART_GENIIE_USER}" -p "${ART_GENIIE_API_KEY}" art.geniie.net || action_status="${LINENO} Failed to docker login."
    docker pull ${docker_image} || action_status="${LINENO} Failed to docker pull."
    if [[ -e ${docker_local_file} ]]; then rm -fr ${docker_local_file}; fi
    docker save -o ${docker_local_file} ${docker_image} || action_status="${LINENO} Failed to docker save."
    echo -n ${build_docker_date} >${WORK_PATH}/tool/build_docker_version.txt
  else
    docker load --input ${docker_local_file} || action_status="${LINENO} Failed to docker load."
  fi
else
  # reset and delete backup
  if [[ -n ${current_image_id} ]]; then 
     docker rmi -f ${current_image_id} || action_status="${LINENO} Failed to docker rmi."
  fi
  if [[ -e ${docker_backup_file} ]]; then 
    docker load --input ${docker_backup_file} || action_status="${LINENO} Failed to docker load."
    rm -fr ${docker_backup_file}
  fi
fi

# create or destroy http proxy and yocto build command alias
if [[ "${action}" == "backup_init" ]]; then
  # backup
  if [[ -e ${HOME}/.bashrc ]]; then 
    cp -fr ${HOME}/.bashrc ${WORK_PATH}/tool/backup/
  fi
  # init http proxy
  if grep http-rpoxy ${HOME}/.bashrc >/dev/null; then
    sed -i '/^########## http-rpoxy ##########/d' ${HOME}/.bashrc
    sed -i '/^export http_proxy=/d' ${HOME}/.bashrc
    sed -i '/^export https_proxy=/d' ${HOME}/.bashrc
    sed -i '/^export no_proxy=/d' ${HOME}/.bashrc
  fi
  echo "########## http-rpoxy ##########" >> ${HOME}/.bashrc
  echo "export http_proxy=\"${HTTP_PROXY}\"" >> ${HOME}/.bashrc
  echo "export https_proxy=\"${HTTPS_PROXY}\"" >> ${HOME}/.bashrc
  echo "export no_proxy=\"${NO_PROXY}\"" >> ${HOME}/.bashrc

  # init yocto build command alias 
  if grep bev-ycbuild ${HOME}/.bashrc >/dev/null; then
    sed -i '/^########## bev yocto build command/d' ${HOME}/.bashrc
    sed -i '/^alias bev-ycbuild/d' ${HOME}/.bashrc

    sed -i "/^export GENIIE_ID=${ART_GENIIE_USER}/d" ${HOME}/.bashrc
    sed -i "/^export GENIIE_PASSWORD=${ART_GENIIE_API_KEY}/d" ${HOME}/.bashrc
  fi
  echo "########## bev yocto build command ##########" >> ${HOME}/.bashrc
  echo "alias bev-ycbuild=${WORK_PATH}/tool/ct-poky" >> ${HOME}/.bashrc

  echo "export GENIIE_ID=${ART_GENIIE_USER}" >> ${HOME}/.bashrc
  echo "export GENIIE_PASSWORD=${ART_GENIIE_API_KEY}" >> ${HOME}/.bashrc
else
  # reset and delete backup
  if [[ -e ${WORK_PATH}/tool/backup/.bashrc ]]; then 
    cp -fr ${WORK_PATH}/tool/backup/.bashrc ${HOME}/
    rm -fr ${WORK_PATH}/tool/backup/.bashrc
  else
    rm -fr ${HOME}/.bashrc
  fi
fi

# main
if [[ "${action}" == "backup_init" ]]; then  
  if [[ ${action_status} != "OK" ]]; then
    echo -e "\e[1;31mThe Yocto Build environment initialization failed. The reason:\e[0m"
    echo -e "\e[1;31m    ${action_status}\e[0m"
    exit 1
  fi
  clear
  echo 'USAGE:'
  echo "  source ${HOME}/.bashrc"
  echo "  bev-ycbuild <directory>"
  echo "reset" > ${WORK_PATH}/tool/backup/action
else
  if [[ ${action_status} != "OK" ]]; then
    echo -e "\e[1;31mThe basic environment reset failed. The reason:\e[0m"
    echo -e "\e[1;31m    ${action_status}\e[0m"
    exit 1
  fi
  echo "The basic environment was reset successfully!"
  echo "backup_init" > ${WORK_PATH}/tool/backup/action
fi
exit 0
